package com.bankcard.card;

import com.bankcard.util.CardNumberFormatter;

import java.util.Objects;

public final class AccountNumber {
    private final String rawNumber;

    public AccountNumber(String number) {
        Objects.requireNonNull(number, "Account number cannot be null");
        this.rawNumber = CardNumberFormatter.removeNonDigits(number);
        validateNumber();
    }

    private void validateNumber() {
        if (!LuhnValidator.isValid(rawNumber)) {
            throw new IllegalArgumentException("Invalid account number");
        }
    }

    public String getRawNumber() {
        return rawNumber;
    }

    public String getFormattedNumber() {
        return CardNumberFormatter.format(rawNumber);
    }

    public String getFormattedNumber(String pattern) {
        return (pattern == null || pattern.isEmpty()) ? getFormattedNumber() : CardNumberFormatter.formatWithPattern(rawNumber, pattern);
    }

    public String getLastFourDigits() {
        return rawNumber.substring(Math.max(0, rawNumber.length() - 4));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        AccountNumber that = (AccountNumber) o;
        return rawNumber.equals(that.rawNumber);
    }

    @Override
    public int hashCode() {
        return Objects.hash(rawNumber);
    }

    @Override
    public String toString() {
        return getFormattedNumber();
    }
}